
<template>
  <a-modal
    v-model="visible"
    :title="isEdit ? $t('subject.autotext1') : $t('all.autotext1462')"
    width="1000px"
    :footer="null"
    @cancel="handleCancel"
  >
    <a-form-model
      :model="form"
      :rules="formRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      ref="formRef"
    >
      <a-form-model-item :label="$t('all.autotext949')" prop="researchId">
        <a-select
          v-model="form.researchId"
          :placeholder="$t('all.autotext444')"
          :disabled="isEdit"
          option-filter-prop="children"
          show-search
          filter
          @change="researchChange"
        >
          <a-select-option v-for="item in allCenterList" :key="item.id" :value="item.id">
            {{
              `${item.researchCenterNo} - ${item.orgName}`
            }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1357')" prop="ptsNo">
        <a-input
          :disabled="isEdit"
          v-model="form.ptsNo"
          :placeholder="$t('all.autotext57')"
          @change="e => handleInputChange(e.target.value)"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext56')" prop="ptsName">
        <a-input v-model="form.ptsName" :disabled="ptsAuthStatus" :placeholder="$t('all.autotext282')">
          <a-tooltip slot="suffix" :title="$t('subject.autotext31')" v-if="ptsAuthStatus">
            <a-icon type="info-circle" class="input-icon" />
          </a-tooltip>
        </a-input>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1053')" prop="ptsPhone" :rules="isPtsPhoneRule">
        <a-input v-model="form.ptsPhone" :disabled="ptsAuthStatus">
          <a-tooltip slot="suffix" :title="$t('subject.autotext31')" v-if="ptsAuthStatus">
            <a-icon type="info-circle" class="input-icon" />
          </a-tooltip>
        </a-input>
      </a-form-model-item>
      <a-form-model-item v-if="ptsPhoneCheck" :label="$t('subject.autotext9')" prop="ptsWechat">
        <div>
          <a-radio-group v-model="form.ptsWechat" :disabled="ptsAuthStatus">
            <a-radio :value="1">{{ $t('all.autotext279') }}</a-radio>
            <a-radio :value="0">{{ $t('all.autotext957') }}</a-radio>
          </a-radio-group>
          <a-tooltip>
            <template slot="title">
              {{ $t('subject.autotext26') }}
            </template>
            <a-icon class="wechat-icon" type="question-circle" />
          </a-tooltip>
        </div>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1466')" prop="ptsStatus">
        <a-select v-model="form.ptsStatus" >
          <a-select-option v-for="(item, index) in $const.RELATION_STATUS" :key="index" :value="item.value">{{ item.desc }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext192')" prop="evidenceType">
        <a-select v-model="form.evidenceType" :disabled="ptsAuthStatus" @change="evidenceChange">
          <a-tooltip slot="suffixIcon" :title="$t('subject.autotext31')" v-if="ptsAuthStatus">
            <a-icon type="info-circle" class="input-icon select-icon" />
          </a-tooltip>
          <a-select-option v-for="(item, index) in $const.DOCUMENT_TYPE" :key="index" :value="item.value">{{ item.desc }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item
        v-if="form.evidenceType"
        :label="$t('all.autotext1359')"
        prop="ptsIdentity"
        :rules="isPtsIdentityRule"
      >
        <a-input v-model="form.ptsIdentity" :disabled="ptsAuthStatus" :placeholder="$t('all.autotext1204')">
          <a-tooltip slot="suffix" :title="$t('subject.autotext31')" v-if="ptsAuthStatus">
            <a-icon type="info-circle" class="input-icon" />
          </a-tooltip>
        </a-input>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext421')" prop="researchDetailId">
        <a-select v-model="form.researchDetailId" allowClear >
          <a-select-option v-for="item in theDoctorList" :value="item.id" :key="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- 受托人 -->
      <a-form-model-item :label="$t('subject.autotext2')" prop="hasGuardian">
        <!-- :disabled="guardianAuthStatus" -->
        <a-switch v-model="hasGuardian" @change="hasGuardianChange"/>
      </a-form-model-item>
      <template v-if="hasGuardian">
        <a-form-model-item :label="$t('subject.autotext3')" prop="guardianName">
          <a-input v-model="form.guardianName" :placeholder="$t('subject.autotext5')" :disabled="guardianAuthStatus">
            <a-tooltip slot="suffix" :title="$t('subject.autotext32')" v-if="guardianAuthStatus">
              <a-icon type="info-circle" class="input-icon" />
            </a-tooltip>
          </a-input>
        </a-form-model-item>
        <a-form-model-item :label="$t('subject.autotext4')" prop="guardianPhone">
          <a-input v-model="form.guardianPhone" :disabled="guardianAuthStatus">
            <a-tooltip slot="suffix" :title="$t('subject.autotext32')" v-if="guardianAuthStatus">
              <a-icon type="info-circle" class="input-icon" />
            </a-tooltip>
          </a-input>
        </a-form-model-item>
        <a-form-model-item v-if="guardianPhoneCheck" :label="$t('subject.autotext9')" prop="guardianWechat">
          <div>
            <a-radio-group v-model="form.guardianWechat" :disabled="guardianAuthStatus">
              <a-radio :value="1">{{ $t('all.autotext279') }}</a-radio>
              <a-radio :value="0">{{ $t('all.autotext957') }}</a-radio>
            </a-radio-group>
            <a-tooltip>
              <template slot="title">
                {{ $t('subject.autotext26') }}
              </template>
              <a-icon class="wechat-icon" type="question-circle" />
            </a-tooltip>
          </div>
        </a-form-model-item>
        <a-form-model-item :label="$t('all.autotext192')" prop="guardianEvidenceType">
          <a-select v-model="form.guardianEvidenceType" @change="evidenceGuardianChange" :disabled="guardianAuthStatus">
            <a-tooltip slot="suffixIcon" :title="$t('subject.autotext32')" v-if="guardianAuthStatus">
              <a-icon type="info-circle" class="input-icon select-icon" />
            </a-tooltip>
            <a-select-option v-for="(item, index) in $const.DOCUMENT_TYPE" :key="index" :value="item.value">{{ item.desc }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          v-if="form.guardianEvidenceType"
          :label="$t('all.autotext1359')"
          prop="guardianIdentity"
          :rules="isGuardianIdentityRule"
        >
          <a-input v-model="form.guardianIdentity" :placeholder="$t('all.autotext1204')" :disabled="guardianAuthStatus">
            <a-tooltip slot="suffix" :title="$t('subject.autotext32')" v-if="guardianAuthStatus">
              <a-icon type="info-circle" class="input-icon" />
            </a-tooltip>
          </a-input>
        </a-form-model-item>
        <a-form-model-item :label="$t('all.autotext1492')" prop="relation">
          <a-select v-model="form.relation">
            <a-select-option v-for="(item, index) in $const.RELATION_TYPE" :key="index" :value="item.value">{{ item.desc }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :label="$t('subject.autotext37')" prop="upload">
          <a-upload
            name="file"
            accept=".pdf, .jpg, .jpeg, .png"
            :file-list="fileList"
            :customRequest="handleCustom"
            @change="handleChange"
          >
            <a-button :disabled="fileList.length>0">{{ $t('all.autotext565') }}</a-button>
          </a-upload>
          <!-- <a-button class="download" type="primary" @click="handleDownloadProve">{{ $t('all.autotext626') }}</a-button> -->
        </a-form-model-item>
      </template>
      <a-form-model-item :label="$t('subject.autotext7')" v-if="this.offline === 1" prop="uploadInfo">
        <a-upload
          name="file"
          accept=".pdf, .jpg, .jpeg, .png"
          :file-list="fileInfoList"
          :customRequest="handleInfoCustom"
          @change="handleInfoChange"
        >
          <a-button v-if="fileInfoList.length===0">{{ $t('subject.autotext23') }}</a-button>
        </a-upload>
        <a-space class="download">
          <a-button v-if="fileInfoList.length===0" type="primary" @click="downnloadInfo">
            {{ $t('all.autotext626') }}
          </a-button>
          <a-tooltip v-if="fileInfoList.length===0">
            <template slot="title">
              {{ $t('all.autotext1788') }}
            </template>
            <a-icon type="info-circle" theme="filled" style="font-size: 20px;" />
          </a-tooltip>
        </a-space>
      </a-form-model-item>
      <template v-if="fileInfoList.length>0 && this.offline === 1">
        <div class="sure">{{ $t('subject.autotext24') }}</div>
        <a-form-model-item prop="authorizationWechat" :wrapperCol="{span: 14, offset: 8}">
          <a-radio-group v-model="form.authorizationWechat">
            <a-radio :value="1">{{ $t('all.autotext279') }}</a-radio>
            <a-radio :value="0">{{ $t('all.autotext957') }}</a-radio>
          </a-radio-group>
        </a-form-model-item>
      </template>
    </a-form-model>
    <div class="message" v-if="hasPhone && phoneCheck">{{ $t('subject.autotext28') }}</div>
    <div class="footer">
      <a-space>
        <a-button @click="handleCancel">{{ $t('all.autotext1578') }}</a-button>
        <template v-if="isEdit">
          <a-button type="primary" @click="handleSave(true)">{{ $t('all.autotext321') }}</a-button>
        </template>
        <template v-else>
          <a-button @click="handleSave(false)">{{ $t('subject.autotext8') }}</a-button>
          <a-button type="primary" @click="handleSave(true)">{{ $t('all.autotext409') }}</a-button>
        </template>
      </a-space>
    </div>
  </a-modal>
</template>

<script>
import { getContractCenter } from '@/api/overview/member'
import { doctorList, addPts, editPts, informationDoc, isExistsFeeApplying } from '@/api/overview/subject'
import { uploadFile } from '@/api/common'

export default {
  data () {
    return {
      proId: '',
      visible: false,
      isEdit: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      form: {
        researchId: undefined,
        ptsNo: undefined,
        ptsName: undefined,
        ptsPhone: undefined,
        ptsStatus: undefined,
        evidenceType: undefined,
        ptsIdentity: undefined,
        researchDetailId: undefined,
        guardianName: undefined,
        guardianPhone: undefined,
        guardianEvidenceType: undefined,
        guardianIdentity: undefined,
        relation: undefined,
        authorizationWechat: undefined,
        source: 1,
        ptsWechat: 1,
        guardianWechat: 1
      },
      formRules: {
        researchId: [{ required: true, message: this.$t('all.autotext444'), trigger: 'blur' }],
        ptsNo: [{ required: true, message: this.$t('all.autotext57'), trigger: 'blur' }],
        ptsName: [{ required: true, message: this.$t('all.autotext282'), trigger: 'blur' }],
        ptsStatus: [{ required: true, message: this.$t('all.autotext356'), trigger: 'change' }],
        identity: [
          { pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/, message: this.$t('all.autotext1052') }
        ],
        identityOther: [
          { required: false, message: this.$t('all.autotext1204'), trigger: 'blur' }
        ],
        guardianName: [{ required: true, message: this.$t('subject.autotext5'), trigger: 'blur' }],
        relation: [{ required: true, message: this.$t('all.autotext1348'), trigger: 'change' }],
        guardianPhone: [
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: this.$t('all.autotext140') }
        ],
        phone: [
          { required: true, message: this.$t('all.autotext396'), trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: this.$t('all.autotext140') }
        ],
        noPhone: [
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: this.$t('all.autotext140') }
        ],
        ptsWechat: [{ required: true, message: this.$t('all.autotext1348'), trigger: 'change' }],
        guardianWechat: [{ required: true, message: this.$t('all.autotext1348'), trigger: 'change' }],
        authorizationWechat: [{ required: true, message: this.$t('subject.autotext25'), trigger: 'change' }]
      },
      hasGuardian: false,
      oldHasGuardian: false,
      allCenterList: [],
      theDoctorList: [], // 显示当前项目研究人员
      fileList: [],
      fileInfoList: [],
      offline: 1,
      hasPhone: false,
      ptsAuthStatus: false,
      guardianAuthStatus: false,
      authorizationList: [],
      isExistApplying: false
    }
  },
  computed: {
    isPtsPhoneRule () {
      return this.hasGuardian ? this.formRules.noPhone : (this.offline === 1 ? this.formRules.phone : this.formRules.noPhone)
    },
    isPtsIdentityRule () {
      return this.form.evidenceType === 1 ? this.formRules.identity : this.formRules.identityOther
    },
    isGuardianIdentityRule () {
      return this.form.guardianEvidenceType === 1 ? this.formRules.identity : this.formRules.identityOther
    },
    ptsPhoneCheck () {
      if (/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.form.ptsPhone)) {
        return true
      } else {
        return false
      }
    },
    guardianPhoneCheck () {
      if (/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.form.guardianPhone)) {
        return true
      } else {
        return false
      }
    },
    phoneCheck () {
      if (/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.form.guardianPhone) || /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.form.ptsPhone)) {
        return false
      } else {
        return true
      }
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.proId = parseInt(pd)
    }
  },
  mounted () {
    this.getAllCenterList()
    this.handleDownloadAuthorization()
  },
  methods: {
    open (params) {
      this.visible = true
      if (params) {
        this.isEdit = true
        this.getDetail(params)
      } else {
        this.isEdit = false
      }
    },
    getDetail (params) {
      let obj = {
        id: params.id,
        researchId: params.researchId,
        ptsNo: params.ptsNo,
        ptsName: params.ptsName,
        ptsPhone: params.ptsPhone,
        ptsWechat: params.ptsWechat,
        ptsStatus: params.ptsStatus,
        evidenceType: params.evidenceType,
        ptsIdentity: params.ptsIdentity,
        researchDetailId: params.researchDetailId,
        guardianName: params.guardianName,
        guardianPhone: params.guardianPhone,
        guardianWechat: params.guardianWechat,
        guardianEvidenceType: params.guardianEvidenceType,
        guardianIdentity: params.guardianIdentity,
        relation: params.relation,
        authorizationWechat: params.authorizationWechat,
        guardianId: params.guardianId
      }
      this.form = obj
      this.offline = params.offline
      this.ptsAuthStatus = params.ptsAuthStatus
      this.guardianAuthStatus = params.guardianAuthStatus
      this.oldHasGuardian = params.hasGuardian
      this.hasGuardian = params.hasGuardian
      this.fileList = params.fileList.map(item => {
        return {
          ...item,
          url: this.$options.filters.dealImageUrl(item.response)
        }
      })
      this.fileInfoList = params.fileInfoList.map(item => {
        return {
          ...item,
          url: this.$options.filters.dealImageUrl(item.response)
        }
      })
      this.getDoctorList(params.researchId)
      this.getIsExistsFeeApplying(params.id, params.guardianId)
    },
    getIsExistsFeeApplying (id, guardianId) {
      isExistsFeeApplying({ id, guardianId, proId: this.proId }).then((res) => {
        this.isExistApplying = res.isExist
      })
    },
    // 获取所有中心下拉列表
    getAllCenterList () {
      getContractCenter({ proId: this.proId, deleted: 0 }).then(res => {
        this.allCenterList = res.content
      })
    },
    // 请求当前项目研究人员列表
    async getDoctorList (e) {
      const res = await doctorList({ proId: this.proId, researchId: e })
      this.theDoctorList = res
    },
    researchChange (e) {
      this.getDoctorList(e)
      const res = this.allCenterList.filter(item => item.id === e)[0]
      if (res.offline) {
        this.offline = res.offline
      } else {
        this.$message.error(this.$t('subject.autotext29'))
        this.form.researchId = undefined
      }
    },
    // input输入事件
    handleInputChange (value) {
      this.form.ptsNo = this.$options.filters.checkUnChinese(value)
    },
    evidenceChange (e) {
      this.$refs.formRef.clearValidate('ptsIdentity')
    },
    evidenceGuardianChange (e) {
      this.$refs.formRef.clearValidate('guardianIdentity')
    },
    hasGuardianChange (e) {
      this.$refs.formRef.clearValidate('ptsPhone')
      this.$refs.formRef.clearValidate('guardianPhone')
      this.$refs.formRef.clearValidate('ptsWechat')
      this.$refs.formRef.clearValidate('guardianWechat')
      if (!e && this.isExistApplying) {
        this.$confirm({
          title: '提示',
          content: h => <div>该受托人当前存在未完成支付的申请单，若取消或变更受托人，需要重新提交申请单，是否确认取消或变更受托人</div>,
          onCancel: () => {
            this.hasGuardian = true
          }
        })
      }
    },
    handleCustom (file) {
      const params = new FormData()
      params.append('file', file.file)
      uploadFile(params).then(res => {
        file.onSuccess(res, file.file)
      }).catch(() => {
        this.fileList = []
        this.$message.error(this.$t('all.autotext1259'))
      }).finally(() => {})
    },
    handleChange ({ file, fileList }) {
      this.fileList = fileList.map(item => {
        return {
          ...item,
          url: this.$options.filters.dealImageUrl(item.response)
        }
      })
    },
    handleInfoCustom (file) {
      const params = new FormData()
      params.append('file', file.file)
      uploadFile(params).then(res => {
        file.onSuccess(res, file.file)
      }).catch(() => {
        this.fileInfoList = []
        this.$message.error(this.$t('all.autotext1259'))
      }).finally(() => {})
    },
    handleInfoChange ({ file, fileList }) {
      this.fileInfoList = fileList.map(item => {
        return {
          ...item,
          url: this.$options.filters.dealImageUrl(item.response)
        }
      })
    },
    handleSave (e) {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (this.offline === 1 && !(this.form.ptsPhone || this.form.guardianPhone)) {
          this.hasPhone = true
          return
        } else {
          this.hasPhone = false
        }
        const params = {
          ...this.form,
          isEnableGuardian: this.hasGuardian ? 1 : 0,
          guardianName: this.hasGuardian ? this.form.guardianName : '',
          guardianPhone: this.hasGuardian ? this.form.guardianPhone : '',
          guardianWechat: this.hasGuardian ? this.form.guardianWechat : '',
          guardianEvidenceType: this.hasGuardian ? this.form.guardianEvidenceType : '',
          guardianIdentity: this.hasGuardian ? this.form.guardianIdentity : '',
          relation: this.hasGuardian ? this.form.relation : '',
          proveFileUrl: (this.hasGuardian && this.fileList.length > 0) ? this.fileList[0].response : '',
          authorizationDocUrl: this.fileInfoList.length > 0 ? this.fileInfoList[0].response : ''
        }
    
        if (this.isEdit) {
          await editPts({
            proId: this.proId,
            ...params
          })
        } else {
          await addPts({
            proId: this.proId,
            proManagePtsList: JSON.stringify([params])
          })
        }
        this.hasPhone = false
        this.hasGuardian = false
        this.fileList = []
        this.fileInfoList = []
        this.$refs.formRef.resetFields()
        this.$message.success(this.$t('all.autotext470'))
        this.$emit('handleSuccess')
        if (e) {
          this.visible = false
        }
      })
    },
    handleCancel () {
      this.hasPhone = false
      this.hasGuardian = false
      this.fileList = []
      this.fileInfoList = []
      this.$refs.formRef.resetFields()
      this.visible = false
    },
    downnloadInfo () {
      window.open(this.$options.filters.dealImageUrl(this.authorizationList[1].content), '_blank')
    },
    async handleDownloadAuthorization () {
      const res = await informationDoc()
      this.authorizationList = res
    }
  }
}
</script>

<style lang="less" scoped>
.wechat-icon {
  font-size: 18px;
  color: #666;
  position: absolute;
  top: 10px;
  right: 0;
  cursor: pointer;
}
.download {
  position: absolute;
  top: -6px;
  right: 0;
}
.sure {
  padding-left: 33%;
  &::before {
    content: '*';
    display: inline-block;
    margin-right: 4px;
    color: #f5222d;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
  }
}
.message {
  font-size: 14px;
  color: #f5222d;
  padding-left: 100px;
}
.input-icon {
  font-size: 18px;
}
.select-icon {
  margin-top: -2px;
}
.footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}
</style>
